<?php

namespace App\Http\Resources;

use App\Helpers\BaseResource;

class User extends BaseResource
{
    public function toArray($request)
    {

        return $this->filterFields([
            'id' => hashid_encode($this->id),
            'name' => $this->name,
            'avatar' => $this->avatar,
            'intro' => (string)$this->intro,
            'doc_num' => $this->whenLoaded('docs', function () {
                return collect($this->docs)->count();
            }),
            'comment_num' => $this->whenLoaded('comments', function () {
                return collect($this->comments)->count();
            }),
            'is_follow' => $this->when($this->ckFields('is_follow'), function () {
                $user = $this->getUser();
                if ($user) {
                    return (bool)$this->isFollowedBy($user);
                } else {
                    return false;
                }
            }),
            'subscribe_doc' => $this->when($this->ckFields('subscribe'), function () {
                return \Cache::remember('user-subscribe-doc-' . $this->id, 10, function () {
                    return $this->subscriptions(\App\Models\Doc::class)->count();
                });
            }),
            'follow' => $this->whenLoaded('followings', function () {
                return collect($this->followings)->count();
            }),
            'fans' => $this->whenLoaded('followers', function () {
                return collect($this->followers)->count();
            }),
            'gender' => $this->when($this->ckFields('gender'), function () {
                return $this->wx_user->gender;
            }),
            'province' => $this->when($this->ckFields('province'), function () {
                return $this->wx_user->province;
            }),
            'city' => $this->when($this->ckFields('city'), function () {
                return $this->wx_user->city;
            }),
            'money' => (float)$this->money,
            'sum_money' => (float)$this->sum_money,
            'liveroom_sum_money' => (float)$this->liveroom_sum_money,
            'tg_sum_money' => (float)$this->tg_sum_money,
            'qd_sum_money' => (float)$this->qd_sum_money,
        ]);
    }
}
